package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.alibaba.fastjson.JSONObject;
import com.beiding.jsonanalyzer.analyze.func.OneFunc;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.analyze.func.base.OneFuncAdaptor;

/**
 * 类型强转
 *
 * @author 丁常磊
 * @date 2022/5/10 13:43
 */

public class Cast {


    public static OneFunc of(Object exp, Class targetType) {
        return FuncUtils.buildForEasyFunc(new OneFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object v) {
                        if (targetType.isInstance(v)) {
                            return v;
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("o", v);
                        try {
                            return jsonObject.getObject("o", targetType);
                        } catch (Exception e) {
                            throw new RuntimeException("不支持的类型强转 值:" + v + " 目标类型:" + targetType, e);
                        }
                    }

                    @Override
                    public String toString() {
                        return "cast(" + core + "," + targetType + ")";
                    }
                };
            }
        }, exp);
    }

}
